package com.cn.http;

import cn.com.allunion.sms.pojo.Smsrecord;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 执行链，用来控制执行拦截器
 * @author yang.jie
 * @email yang.jie@all-union.com.cn
 * @date 2016/5/5.
 * @copyright http://www.all-union.com.cn/
 */
public class HandlerExecutionChain {
    private static final Logger LOGGER = LoggerFactory.getLogger(HandlerExecutionChain.class) ;
    /**
     * 处理器，暂时没有用到
     */
    private Object handler ;

    /**
     * 拦截器集合
     */
    private List<SmsrecordInterceptor> interceptorList ;

    /**
     * 执行短信发送命令前拦截
     * @param smsrecordList 要拦截的短信发送记录集合
     * @return 拦截成功返回true，否者返回false
     */
    public boolean applyPreExecute(List<Smsrecord> smsrecordList) {
        if (CollectionUtils.isEmpty(smsrecordList)) {
            LOGGER.warn("开始执行拦截器链，短信记录集合为空集合，没有被拦截。");
            return false ;
        }
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("开始执行拦截器链，短信记录数量： {}", smsrecordList.size());
        }
        boolean isIntercepted = false ; // 是否被拦截到了
        SmsrecordInterceptor[] interceptors = getInterceptors() ;
        if (interceptors != null) {
            for (int i = 0; i < interceptors.length; i++) {
                SmsrecordInterceptor interceptor = interceptors[i];
                // 执行拦截操作
                boolean interceptResult = interceptor.preExecute(smsrecordList) ;
                if (!isIntercepted) {
                    isIntercepted = interceptResult ;
                }
            }
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("执行拦截器链结束，短信记录数量： {}， 是否被拦截： {}", smsrecordList.size(), isIntercepted);
        }

        return isIntercepted;
    }


    public Object getHandler() {
        return handler;
    }

    public void setHandler(Object handler) {
        this.handler = handler;
    }

    public List<SmsrecordInterceptor> getInterceptorList() {
        return interceptorList;
    }

    public void setInterceptorList(List<SmsrecordInterceptor> interceptorList) {
        this.interceptorList = interceptorList;
    }

    public SmsrecordInterceptor[] getInterceptors() {
        if (CollectionUtils.isNotEmpty(interceptorList)) {
            return interceptorList.toArray(new SmsrecordInterceptor[this.interceptorList.size()]);
        }
        return null;
    }
}
